from django.shortcuts import render
from rest_framework.generics import RetrieveAPIView,ListAPIView,CreateAPIView,UpdateAPIView,DestroyAPIView,GenericAPIView
# Create your views here.
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework import status
from .serializers import AreasSearializer,AreasAddSerializer,AreasTitleSerializer,AreasStatusSerializer
from .models import Area
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from user.models import Address
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

# class AreasProView(ListAPIView):
#     serializer_class = AreasSearializer
#     queryset = Area.objects.filter(parent=None)
    # get  areas/  id,name
    # def get(self,request):


class AreasCityView(ListAPIView,CacheResponseMixin):
    serializer_class = AreasSearializer

    def get_queryset(self):
        pk = self.kwargs.get('pk')
        print(self.request.path)
        return Area.objects.filter(parent=pk if pk else None)


class LargeResultsSetPagination(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'page_size'
    max_page_size = 10000

class AreasAddView(CreateAPIView,UpdateAPIView):
    serializer_class = AreasAddSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = LargeResultsSetPagination
    def get_queryset(self):
        return Address.objects.filter(is_delete=False,user=self.request.user)

    # post  addresses/
    # title,receiver,province,city,district,place,mobile,tel,email
    # def create(self,request):
        # 获取参数

        # 验证手机号格式

        # 保存地址

        # 返回值

    def get(self,request):
        address = self.get_queryset()
        serializer = self.get_serializer(address,many=True)
        print(serializer.data)
        user = self.request.user
        return Response({'user_id':user.id,
                         'addresses':serializer.data,
                         # 获取用户默认地址的id，不是地址对象
                         'default_address_id':user.default_address.id,
                         'limit':5,})

    def delete(self,request,pk):

        address = self.get_object()

        address.is_delete = True
        address.save()

        return Response({'message':'ok'},status=status.HTTP_200_OK)

# 修改标题
class AreasSetView(UpdateAPIView):
    serializer_class = AreasTitleSerializer
    queryset = Address.objects.filter(is_delete=False)
    permission_classes = [IsAuthenticated]


# 设置默认地址
class AreasStatusView(GenericAPIView):
    serializer_class = AreasStatusSerializer
    permission_classes = [IsAuthenticated]
    queryset = Address.objects.filter(is_delete=False)

    def put(self,request,pk=None):

        user = self.request.user
        print(self.get_object())
        user.default_address = self.get_object()
        user.save()

        return Response({'message':'ok'},status=status.HTTP_200_OK)



